package com.bto.solar.work.fdd.client;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.bto.solar.work.common.BizException;
import com.bto.solar.work.constant.BizCode;
import com.bto.solar.work.constant.Constants;
import com.bto.solar.work.constant.SignTaskStatusEnum;
import com.bto.solar.work.dao.ICustomerService;
import com.bto.solar.work.dao.IFddTaskService;
import com.bto.solar.work.entity.Customer;
import com.bto.solar.work.entity.FddTask;
import com.bto.solar.work.entity.OrderBase;
import com.bto.solar.work.utils.StringUtils;

import com.bto.solar.work.utils.ValidUtils;
import com.fasc.open.api.bean.base.BaseRes;
import com.fasc.open.api.bean.common.*;
import com.fasc.open.api.enums.common.IdTypeEnum;
import com.fasc.open.api.enums.doc.FileTypeEnum;
import com.fasc.open.api.exception.ApiException;
import com.fasc.open.api.v5_1.client.SignTaskClient;
import com.fasc.open.api.v5_1.req.signtask.*;
import com.fasc.open.api.v5_1.res.signtask.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

@Slf4j
@Service
public class FddSignTaskClient {

    @Value("${fdd.open-crop-id}")
    private String openCorpId;
    @Value("${fdd.initiator-member-id}")
    public String initiatorMemberId;

    @Autowired
    private FddBaseClient fddBaseClient;
    @Autowired
    private FddTemplateClient fddTemplateClient;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IFddTaskService fddTaskService;

    /**
     * 创建签署客户端
     */
    public SignTaskClient getFddSignTaskClient() {
        return  new SignTaskClient(fddBaseClient.getFddOpenApiClient());
    }

    /**
     * 获取签署任务详情 --- 接口
     */
    public SignTaskDetailRes getAppDetail(String signTaskId) {
        try {
            SignTaskBaseReq signTaskBaseReq = new SignTaskBaseReq();
            signTaskBaseReq.setAccessToken(fddBaseClient.getFddAccessToken());
            //签署任务id，通过创建签署任务接口返回
            signTaskBaseReq.setSignTaskId(signTaskId);
            BaseRes<SignTaskDetailRes> res = getFddSignTaskClient().getDetail(signTaskBaseReq);
            fddBaseClient.isResultSuccess(res, signTaskId, "signTaskId is {} 获取签署任务详情失败");
            return res.getData();
        } catch (ApiException e) {
            throw new BizException("signTaskId is {} 获取签署任务详情失败 {}", signTaskId, e);
        }
    }

    /**
     * 查询参与方填写内容 --- 接口
     */
    public List<ListSignTaskFillField> getListSignTaskField(String signTaskId) {
        try {
            SignTaskClient signTaskClient = getFddSignTaskClient();
            ListSignTaskFieldReq listSignTaskFieldReq = new ListSignTaskFieldReq();
            //签署任务ID
            listSignTaskFieldReq.setSignTaskId(signTaskId);
            listSignTaskFieldReq.setAccessToken(fddBaseClient.getFddAccessToken());
            BaseRes<ListSignTaskFieldRes> res = signTaskClient.listSignTaskField(listSignTaskFieldReq);
            fddBaseClient.isResultSuccess(res, signTaskId, "签署任务Id: {}, 查询参与方填写内容失败");
            return res.getData().getFillFields();
        } catch (ApiException e) {
            throw new BizException("签署任务Id: {}, 查询参与方填写内容失败", signTaskId);
        }

    }

    /**
     * 获取签署任务预览链接 -- 接口
     */
    public String getSignTaskPreviewUrl(String signTaskId) {
        try {
            GetSignTaskUrlReq getSignTaskUrlReq = new GetSignTaskUrlReq();
            //重定向地址
            getSignTaskUrlReq.setRedirectUrl("http://www.baidu.com");
            //签署任务ID
            getSignTaskUrlReq.setSignTaskId(signTaskId);
            getSignTaskUrlReq.setAccessToken(fddBaseClient.getFddAccessToken());

            BaseRes<GetSignTaskPreviewUrlRes> res = getFddSignTaskClient().getSignTaskPreviewUrl(getSignTaskUrlReq);
            fddBaseClient.isResultSuccess(res, signTaskId, "签署任务Id: {}, 获取签署任务预览链接失败");
            return  res.getData().getSignTaskPreviewUrl();
        } catch (ApiException e) {
            throw new BizException("签署任务Id: {}, 获取签署任务预览链接失败", signTaskId);
        }

    }

    /**
     * 催办签署任务 -- 接口
     */
    public String signTaskUrge(String signTaskId) {
        try {
            SignTaskBaseReq signTaskBaseReq = new SignTaskBaseReq();
            signTaskBaseReq.setAccessToken(fddBaseClient.getFddAccessToken());
            //签署任务id，通过创建签署任务接口返回
            signTaskBaseReq.setSignTaskId(signTaskId);
            return getFddSignTaskClient().signTaskUrge(signTaskBaseReq).getCode();
        } catch (ApiException e) {
            throw new BizException("签署任务Id: {}, 催办签署任务失败", signTaskId);
        }
    }

    /**
     * 获取图片版签署文档下载地址 --- 接口
     */
    public String getSignTaskOwnerPicDownloadUrl (String slicingTicketId) {
        try {
            GetSignTaskPicDocTicketReq req = new GetSignTaskPicDocTicketReq();
            req.setAccessToken(fddBaseClient.getFddAccessToken());
            req.setSlicingTicketId(slicingTicketId);
            BaseRes<GetSignTaskDocRes> getSignTaskDocRes = getFddSignTaskClient().getSignTaskOwnerPicDownloadUrl(req);
            fddBaseClient.isResultSuccess(getSignTaskDocRes, "获取签署方个人照片下载链接失败");
            return getSignTaskDocRes.getData().getDownloadUrl();
        } catch (ApiException e) {
            throw new BizException("获取签署方个人照片下载链接失败");
        }
    }

    /**
     * 获取签署文档切图 --- 接口
     */
    public String getSignTaskOwnerSlicingTicketId (String signTaskId) {
        try {
            GetSignTaskSlicingDocReq req = new GetSignTaskSlicingDocReq();
            OpenId ownerId = new OpenId();
            ownerId.setIdType(IdTypeEnum.CORP.getCode());
            ownerId.setOpenId(openCorpId);
            req.setOwnerId(ownerId);
            req.setAccessToken(fddBaseClient.getFddAccessToken());
            req.setSignTaskId(signTaskId);
            BaseRes<GetSignTaskPicDocTicketRes> getSignTaskPicDocTicketRes = getFddSignTaskClient().getSignTaskOwnerSlicingTicketId(req);
            fddBaseClient.isResultSuccess(getSignTaskPicDocTicketRes, signTaskId,"signTaskId {}, 获取签署文档切图失败");
            return getSignTaskPicDocTicketRes.getData().getSlicingTicketId();
        } catch (ApiException e) {
            throw new BizException("signTaskId {}, 获取签署文档切图失败", signTaskId);
        }
    }

    /**
     *查询企业签署任务文件夹 --- 接口
     */
    public BaseRes<List<SignTaskCatalogListRes>> signTaskCataloglist() {
        try {
            SignTaskCatalogListReq signTaskCatalogListReq = new SignTaskCatalogListReq();
            //签署任务文件夹的归属主体
            OpenId ownerId = new OpenId();
            ownerId.setIdType(IdTypeEnum.CORP.getCode());
            ownerId.setOpenId(openCorpId);
            signTaskCatalogListReq.setOwnerId(ownerId);
            signTaskCatalogListReq.setAccessToken(fddBaseClient.getFddAccessToken());
            BaseRes<List<SignTaskCatalogListRes>> res = getFddSignTaskClient().signTaskCataloglist(signTaskCatalogListReq);
            fddBaseClient.isResultSuccess(res, "查询企业签署任务文件夹失败");
            return getFddSignTaskClient().signTaskCataloglist(signTaskCatalogListReq);
        } catch (ApiException e) {
            throw new BizException(e.getMessage());
        }
    }

    /**
     * 获取指定归属方的签署任务文档下载地址 --- 接口
     */
    public OwnerDownloadUrlRes getOwnerDownloadUrl(String signTaskId) {
        try {
            GetOwnerDownloadUrlReq req = new GetOwnerDownloadUrlReq();
            req.setAccessToken(fddBaseClient.getFddAccessToken());
            //签署任务发起方或参与方
            req.setOwnerId(OpenId.getInstance(IdTypeEnum.CORP.getCode(), openCorpId));
            //签署任务id，通过创建签署任务接口返回
            req.setSignTaskId(signTaskId);
            //（可选）文档类型FileTypeEnum：doc：签署任务中的文档 。 attach：签署任务中的附件。
            req.setFileType(FileTypeEnum.DOC.getCode());
            //（可选）指定签署任务中的文档序号docId或附件序号attachId。
            req.setId(fddTemplateClient.getQyDocId());
            BaseRes<OwnerDownloadUrlRes> res = getFddSignTaskClient().getOwnerDownloadUrl(req);
            fddBaseClient.isResultSuccess(res, signTaskId,"签署任务id : {} , 获取指定归属方的签署任务文档下载地址");
            return res.getData();
        } catch (ApiException e) {
            throw new BizException("签署任务id : {} , 获取指定归属方的签署任务文档下载地址", signTaskId);
        }
    }

    /**
     * 获取指定归属方的签署任务列表 --- 接口
     */
    public GetSignTaskListRes getOwnerList(String signTaskSubject, List<String> signTaskStatusList,
                             int pageNo, int pageSize) {
        try {
            GetOwnerSignTaskListReq req = new GetOwnerSignTaskListReq();
            req.setAccessToken(fddBaseClient.getFddAccessToken());
            //签署任务发起方或参与方主体
            req.setOwnerId(OpenId.getInstance(IdTypeEnum.CORP.getCode(), openCorpId));
            //（可选）主体参与签署协作类型。initiator:  发起方， actor:  参与方(填写、签署)。
            req.setOwnerRole("initiator");
            //（可选）查询条件
            SignTaskListFilter filter = new SignTaskListFilter();
            //（可选）签署任务名称
            filter.setSignTaskSubject(signTaskSubject);
            //（可选）签署任务状态SignTaskStatusEnum，支持传入多个状态
            filter.setSignTaskStatus(signTaskStatusList);
            req.setListFilter(filter);
            //（可选）指定第几页
            req.setListPageNo(pageNo);
            //（可选）指定每页多少条数据
            req.setListPageSize(pageSize);

            BaseRes<GetSignTaskListRes> res = getFddSignTaskClient().getOwnerList(req);
            fddBaseClient.isResultSuccess(res, "获取指定归属方的签署任务列表失败");
            return res.getData();
        } catch (ApiException e) {
            throw new BizException("获取指定归属方的签署任务列表失败！");
        }

    }

    /**
     * 作废签署任务 --- 接口
     */
    public BaseRes<CancelSignTaskCreateRes> abolishSignTask(OrderBase orderBase, String signTaskId, String reason) {
        try {
            CancelSignTaskCreateReq req = createCancelSignTaskCreateReq(orderBase, signTaskId, reason);
            BaseRes<CancelSignTaskCreateRes> res = getFddSignTaskClient().abolishSignTask(req);
            fddBaseClient.isResultSuccess(res, signTaskId,"签署任务Id: {}, 作废签署任务失败");
            return res;
        } catch (ApiException e) {
            throw new BizException("签署任务Id: {}, 作废签署任务失败", signTaskId);
        }
    }


    /**
     * 构建作废请求体
     */
    public CancelSignTaskCreateReq createCancelSignTaskCreateReq(OrderBase orderBase, String signTaskId, String reason) {
        if (null == orderBase || StringUtils.isEmpty(signTaskId)) {
            throw new BizException("订单信息或签署任务Id不能为空！");
        }
        Customer customer = customerService.getById(orderBase.getCustomerId());
        if (customer == null) {
            throw new BizException("找不到客户信息");
        }
        CancelSignTaskCreateReq cancelSignTaskCreateReq = new CancelSignTaskCreateReq();
        //token
        cancelSignTaskCreateReq.setAccessToken(fddBaseClient.getFddAccessToken());
        //已完成的签署任务ID
        cancelSignTaskCreateReq.setSignTaskId(signTaskId);
        //作废发起方，只能是原签署任务的发起方或签署参与方，二选一传入，同时传入会优先取发起方
        CancelSignTaskCreateReq.AbolishedInitiator abortedInitiator = new CancelSignTaskCreateReq.AbolishedInitiator();
        //原签署任务发起方ID
        abortedInitiator.setInitiatorId(openCorpId);
        cancelSignTaskCreateReq.setAbolishedInitiator(abortedInitiator);
        //作废原因
        cancelSignTaskCreateReq.setReason(reason);
        //是否自动提交签署任务
        cancelSignTaskCreateReq.setAutoStart(true);
        //作废协议文档来源，默认platform
        cancelSignTaskCreateReq.setDocSource("selfUpload");
        //自行上传的作废协议文档
        String idCardNumber = customer.getIdNumber();
        if(StringUtils.isEmpty(idCardNumber)){
            throw new BizException("身份证号码为空");
        }
        CancelSignTaskCreateReq.CancelDoc doc = fddTemplateClient.getCancelDoc(customer.getIdNumber());
        List<CancelSignTaskCreateReq.CancelDoc> docList = new ArrayList<>();
        docList.add(doc);
        cancelSignTaskCreateReq.setDocs(docList);

        CancelSignTaskCreateReq.CancelSignTaskActor cancelSignTaskActor = new CancelSignTaskCreateReq.CancelSignTaskActor();
        CancelSignTaskCreateReq.CancelActor actor = new CancelSignTaskCreateReq.CancelActor();



        String actorCustomerId = orderBase.getOrderId();
        String actorCustomerPhone = customer.getPhone();
        String actorCustomerType = "person";  //个人
        String actorCustomerName = customer.getName();
        //参与方权限数组：fill: 填写和确认内容 sign: 确定签署 cc:抄送查看
        List<String> actorCustomerPermission = Collections.singletonList("sign");

        Notification notification = null;
        //法大大送达信息。如果需要法大大送达，需要设置属性Notification.sendNotification=true
        notification = new Notification();
        notification.setSendNotification(true);
        notification.setNotifyWay("mobile");
        notification.setNotifyAddress(actorCustomerPhone);

        //参与方的个人信息
        Actor actorCustomer = FddSignTaskClient.getActor(actorCustomerId, actorCustomerType, actorCustomerName,
                actorCustomerPermission.toArray(new String[0]), null, actorCustomerPhone,
                notification);

        BeanUtils.copyProperties(actorCustomer, actor);
        cancelSignTaskActor.setActor(actor);

        List<CancelSignTaskCreateReq.CancelSignTaskActor> actorList = new ArrayList<>();
        List<CancelSignTaskCreateReq.CancelSignActorField> fieldList = new ArrayList<>();
        for (Field field : fddTemplateClient.getDocTemplateDetail(fddTemplateClient.getZfDocTemplateId())) {
            if (Constants.QZKJ_LIST.contains(field.getFieldType())) {
                CancelSignTaskCreateReq.CancelSignActorField actorField = new CancelSignTaskCreateReq.CancelSignActorField();
                actorField.setFieldDocId(fddTemplateClient.getZfDocId());
                actorField.setFieldId(field.getFieldId());
                fieldList.add(actorField);
            }
        }
        cancelSignTaskActor.setSignFields(fieldList);
        actorList.add(cancelSignTaskActor);
        cancelSignTaskCreateReq.setActors(actorList);
        return cancelSignTaskCreateReq;
    }


    /**
     * 构造参与方对象信息
     * @param actorId 参与方标识。在同一个签署任务中，参与方标识唯一  -- orderId
     * @param actorType 参与方主体类型 --- person
     * @param actorName 参与方具体名称 --- 客户名称
     * @param permissions 参与方权限数组： --- fill: 填写和确认内容；sign: 确定签署
     * @param actorCorpMembers 参与方企业成员列表，用于参与方企业主体成员的身份识别 --- null
     * @param accountName 参与方的法大大帐号，为手机号或邮箱，长度最大60个字符。仅对个人参与方有效 --- 客户手机号
     * @param notification 法大大送达通知信息
     * @return
     */
    public static Actor getActor(String actorId, String actorType, String actorName, String[] permissions,
                                 ActorCorpMember[] actorCorpMembers,
                                 String accountName,
                                 Notification notification) {
        Actor actor = new Actor();
        actor.setActorId(actorId);
        actor.setActorType(actorType);
        actor.setActorName(actorName);
        if (permissions != null) {
            actor.setPermissions(Arrays.asList(permissions));
        }
        actor.setAccountName(accountName);
        if (actorCorpMembers != null) {
            actor.setActorCorpMembers(Arrays.asList(actorCorpMembers));
        }
        actor.setNotification(notification);
        return actor;
    }

    /**
     * 创建 签署方专属连接（签署方通过连接签署）
     */
    public SignTaskActorGetUrlReq createSignTaskActorGetUrlReq(OrderBase orderBase, String signTaskId) {
        SignTaskActorGetUrlReq signTaskActorGetUrlReq = new SignTaskActorGetUrlReq();
        signTaskActorGetUrlReq.setAccessToken(fddBaseClient.getFddAccessToken());

        signTaskActorGetUrlReq.setSignTaskId(signTaskId);
        signTaskActorGetUrlReq.setActorId(orderBase.getOrderId());
        /**应用系统中唯一确定登录用户身份的标识
         * 如应用系统中该用户标识和法大大的账号存在映射关系，则可以实现免登进入签署页面进行签署。
         * 注意：1）该字段可以为空，为空则表示生成的链接不接入账号免登机制。
         *      2）如该字段不为空，则强烈建议和授权时的clientUserId保持一致。
         *      3）clientUserId对应的用户 **无需提前授权** ，和主体资源授权是完全不同的概念。
         */
        signTaskActorGetUrlReq.setClientUserId("");
        try {
            signTaskActorGetUrlReq.setRedirectUrl(URLEncoder.encode("http://biz.btowork.top" , "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new BizException("获取签署方专属链接， 重定向地址错误");
        }
        return signTaskActorGetUrlReq;
    }

    /**
     * 创建 授权个人信息使用协议使用 签署任务
     */
    public CreateSignTaskReq createSignTaskPersonalInfoUsedReq(OrderBase orderBase, String signType) {
        //创建签署任务
        CreateSignTaskReq createSignTaskReq = new CreateSignTaskReq();
        createSignTaskReq.setAccessToken(fddBaseClient.getFddAccessToken());

        //该签署任务的发起方。主体类型IdTypeEnum
        createSignTaskReq.setInitiator(OpenId.getInstance(IdTypeEnum.CORP.getCode(), openCorpId));
        //该签署任务的发起方成员，即该任务的创建者
        createSignTaskReq.setInitiatorMemberId(initiatorMemberId);
        //签署任务主题。
        createSignTaskReq.setSignTaskSubject("个人信息使用授权");
        //签署文档类型：contract：合同 document：单据 **注意：单据类型的签署文档只能有一个参与方**
        createSignTaskReq.setSignDocType("contract");
        //（可选）任务过期时间。格式为：精确到毫秒。该参数时间是未来时间，且和当前时间差不可小于10分钟(600000) 。
        // 30分钟有效期
        Calendar now = Calendar.getInstance();
        now.add(Calendar.MINUTE, 30);
        createSignTaskReq.setExpiresTime(String.valueOf(now.getTimeInMillis()));
        //（可选）是否自动发起。false: 不自动发起 true: 自动发起。默认为false。
        createSignTaskReq.setAutoStart(true);
        //（可选）全部必填控件填写完成后是否自动定稿：false: 不自动定稿 true: 自动定稿 默认为true。
        createSignTaskReq.setAutoFillFinalize(true);
        //（可选）签署流程是否有序：false: 无序 true: 有序 默认为false。
        createSignTaskReq.setSignInOrder(false);
        //（可选）您的业务应用系统中的业务场景信息，用于更好的定义业务场景和签署任务的关系。
        BusinessSceneInfo businessSceneInfo = new BusinessSceneInfo();
        //（可选）免验证签场景码（已审核通过），使用免验证签署时传入，长度最大32个字符。设置免签场景
        // businessSceneInfo.setBusinessId("");
        //（可选）业务参考号，由应用系统基于自身业务上下文提供。长度最大100个字符。该参数用于应用系统和签署任务建立关联关系，方便业务流程和数据的关联，例如可以是电商场景的订单号。
        // 订单编号：客户姓名。
        Customer customer = customerService.getById(orderBase.getCustomerId());
        String transReferenceId = String.format("{}:{}", orderBase.getOrderId(), customer.getName());
        businessSceneInfo.setTransReferenceId(transReferenceId);
        //根据是否需要BusinessScene而传入数据
        //createSignTaskReq.setBusinessScene(businessSceneInfo);
        //要求该模板各参与方使用的印章证书颁发机构,默认无要求
        createSignTaskReq.setCertCAOrg(null);

        //待签署文档列表
        List<AddDocInfo> docs = new ArrayList<>();
        AddDocInfo doc = fddTemplateClient.getDoc();
        //如果在后台设置了控件信息就不要在代码添加，不然会重复添加
        doc.setDocFields(null);
        docs.add(doc);
        createSignTaskReq.setDocs(docs);
        //获取参与方列表
        List<AddActorsInfo> addActorsInfoList = new ArrayList<>();
        //此处个人信息授权协议书 只设置了客户签署信息 如果时多方签署的需要设置多个参与方信息
        addActorsInfoList.add(getPersonalInfoUsedCustomerInfo(orderBase, signType));
        createSignTaskReq.setActors(addActorsInfoList);


        return createSignTaskReq;
    }

    /**
     * 构建 参与方列表-客户  签署信息
     */
    private AddActorsInfo getPersonalInfoUsedCustomerInfo(OrderBase orderBase, String signWay) {
        String orderId = orderBase.getOrderId();
        Customer customer = customerService.getById(orderBase.getCustomerId());
        if (null == customer) {
            throw new BizException("创建个人信息，法大大签署方信息失败--获取客户信息失败");
        }
        String actorCustomerPhone = customer.getPhone();
        //校验电话号码
        ValidUtils.isPhoneNum(actorCustomerPhone);
        String actorCustomerType = "person";  //个人
        String actorCustomerName = customer.getName();
        //参与方权限数组：fill: 填写和确认内容 sign: 确定签署 cc:抄送查看
        List<String> actorCustomerPermission = Arrays.asList("fill", "sign");

        Notification notification = null;

        if ("sms".equalsIgnoreCase(signWay)) {
            //法大大送达信息。如果需要法大大送达，需要设置属性Notification.sendNotification=true
            notification = new Notification();
            notification.setSendNotification(true);
            notification.setNotifyWay("mobile");
            notification.setNotifyAddress(actorCustomerPhone);
        }


        //参与方的个人信息
        Actor actorCustomer = FddSignTaskClient.getActor(orderId, actorCustomerType, actorCustomerName,
                actorCustomerPermission.toArray(new String[0]), null, actorCustomerPhone,
                notification);
        //签署信息请求体
        AddActorsInfo addActorsInfo = new AddActorsInfo();
        //参与方的个人信息
        addActorsInfo.setActor(actorCustomer);

        //获取法大大系统编辑好的文档模板的控件信息（包含了填写类控件和签署类控件）
        AddDocInfo personalInfoUsedSignDoc = fddTemplateClient.getDoc();

        //填写的控件信息列表
        List<AddFillFieldInfo> addFillFieldInfos = new ArrayList<>();
        personalInfoUsedSignDoc.getDocFields().forEach(docfield -> {
            if (!Constants.QZKJ_LIST.contains(docfield.getFieldType())) {
                //所在的文档序号
                String fieldDocId = personalInfoUsedSignDoc.getDocId();
                //字段id
                String fieldId = docfield.getFieldId();
                //字段类型
                String fieldType = docfield.getFieldType();
                //字段名称
                String fieldName = docfield.getFieldName();

                AddFillFieldInfo fillFieldInfo = new AddFillFieldInfo();
                fillFieldInfo.setFieldDocId(fieldDocId);
                fillFieldInfo.setFieldId(fieldId);
                //控件名称(不推荐)。如果未提供fieldId参数，也可以指定控件名称，因为多个控件可能在一个文档中重名，则最终可能关联多个控件
                // 注意：如果提供了fieldId参数，则该参数会被忽略
                fillFieldInfo.setFieldName(fieldName);
                //控件缺省填充值。该值将会展示给该参与方，但该参与方可修改和确认，用于业务预先知道应填内容，但需要参与方确认的场景。
                //注意：填充控件的值格式与控件类型相关  不设置初始值
                fillFieldInfo.setFieldValue(null);
                //自动填充身份证号码
                if(Constants.FDD_FIELD_NAME.equals(fieldName)){
                    boolean[] booleans = {true};
                    fillFieldInfo.setFieldValue(Arrays.toString(booleans));
                }
                addFillFieldInfos.add(fillFieldInfo);
            }
        });

        // 签署控件的信息列表
        List<AddSignFieldInfo> addSignFieldInfos = new ArrayList<>();
        personalInfoUsedSignDoc.getDocFields().forEach(docfield -> {
            if (Constants.QZKJ_LIST.contains(docfield.getFieldType())) {
                //所在的文档序号
                String fieldDocId = personalInfoUsedSignDoc.getDocId();
                //字段id
                String fieldId = docfield.getFieldId();
                //字段名称
                String fieldName = docfield.getFieldName();

                AddSignFieldInfo addSignFieldInfo = new AddSignFieldInfo();
                addSignFieldInfo.setFieldDocId(fieldDocId);
                addSignFieldInfo.setFieldId(fieldId);
                addSignFieldInfo.setFieldName(fieldName);
                addSignFieldInfo.setSealId(null);
                addSignFieldInfo.setMoveable(false);
                addSignFieldInfos.add(addSignFieldInfo);
            }
        });


        addActorsInfo.setFillFields(addFillFieldInfos);
        addActorsInfo.setSignFields(addSignFieldInfos);
        //设置签署配置 -- 只能手绘
        AddSignConfigInfo addSignConfigInfo = new AddSignConfigInfo();
        /**
        *个人或企业经办人签名方式，默认为unlimited
         * unlimited: 不限制 (可用系统支持的方式)
         * standard: 标准签名 (系统创建的标准签名)，示意图：标准签名.png,50
         * hand_write: 手绘签名 ，示意图：手绘签名.png,50
         * ai_hand_write：使用AI手绘签名，手写字迹会通过Al轨迹识别。示意图：AI手绘.jpg,50
        */
        addSignConfigInfo.setSignerSignMethod("hand_write");
        addActorsInfo.setSignConfigInfo(addSignConfigInfo);

        return addActorsInfo;
    }




    /**
     * 判断是否再次创建签署任务
     */
    public void isCreateSignTask(String orderId) {
        //先通过数据库查询该订单是否已经创建签署任务--查询最新的记录
        FddTask fddTask = fddTaskService.lambdaQuery()
                .eq(FddTask::getOrderId, orderId)
                .orderByDesc(FddTask::getCreateTime).last("limit 1").one();
        //属于已逾期/已作废/任务异常停止就false
        if (null != fddTask && isCanCreateSignTask(fddTask.getSignTaskStatus())) {
            //再通过签署任务ID进行签署任务详情查询--查询状态
            SignTaskDetailRes signTaskDetailRes = getAppDetail(fddTask.getSignTaskId());
            if (null != signTaskDetailRes) {
                if (!signTaskDetailRes.getSignTaskStatus().equals(fddTask.getSignTaskStatus())) {
                    //更新签署任务状态
                    LambdaUpdateWrapper<FddTask> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(FddTask::getSignTaskId, fddTask.getSignTaskId()).eq(FddTask::getOrderId, orderId)
                            .set(FddTask::getSignTaskStatus, signTaskDetailRes.getSignTaskStatus());
                    fddTaskService.update(null, updateWrapper);
                }
                //属于已逾期/已作废/任务异常停止就false
                if (SignTaskStatusEnum.ABOLISHING.getStatus().equals(signTaskDetailRes.getSignTaskStatus())) {
                    throw new BizException("该订单签署任务处于作废中，请先作废完成后，再次创建！");
                } else if (isCanCreateSignTask(signTaskDetailRes.getSignTaskStatus())) {
                    throw new BizException("该订单已经创建签署任务，请勿重复创建");
                }
            }
        }
    }

    /**
     * 判断该订单是否可以再次创建签署任务
     */
    public  boolean isCanCreateSignTask(String signTaskStatus) {
        if (StringUtils.isEmpty(signTaskStatus)) {
            throw new BizException(BizCode.PARAM_ERROR);
        }
        //已逾期/已作废/任务异常停止 --- !true = false
        return !(SignTaskStatusEnum.EXPIRED.getStatus().equals(signTaskStatus)
                || SignTaskStatusEnum.REVOKED.getStatus().equals(signTaskStatus)
                || SignTaskStatusEnum.TASK_TERMINATED.getStatus().equals(signTaskStatus));
    }

}
